package com.uam.core.config;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.http.conn.util.InetAddressUtils.isIPv4Address;

/**
 * @author heguanglong
 */
public class IpAndUuidConfig {
    static Pattern pattern = Pattern.compile("\\d+");

    private static String getLocalIp() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * IPv4地址转换为int类型数字
     */
    public static int ipV4ToInteger() {
        try {
            String ipv4Addr = getLocalIp();
            if (!isIPv4Address(ipv4Addr)) {
                throw new RuntimeException("Invalid ip address");
            }
            Matcher matcher = pattern.matcher(ipv4Addr);
            int result = 0;
            int counter = 0;
            while (matcher.find()) {
                int value = Integer.parseInt(matcher.group());
                result = (value << 8 * (3 - counter++)) | result;
            }
            return Math.abs(result);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取鉴权码
     * @param code
     * @return
     */
    public static String authCode(Object code){
        return IpAndUuidConfig.ipV4ToInteger() +"|"+code+"|"+System.currentTimeMillis()+"|"+ UUID.randomUUID().toString();
    }
}
